package com.itmake.sample.easyexcel.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.itmake.sample.easyexcel.service.IDictService;
import com.itmake.sample.easyexcel.util.SpringUtil;

import java.util.Map;

/**
 * 字典转换（string-string）
 *
 * @author Amjacks
 * @since 2023/08/17
 */
public abstract class DictConvert implements Converter<String> {

    // 字典映射
    private Map<String, String> map;

    protected DictConvert(String dictType) {
        // 获取字典集合
        IDictService bean = SpringUtil.getBean(IDictService.class);
        map = bean.getDictDataByType(dictType);
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadCellData cellData,
                                    ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        String key = null;
        if (!map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (entry.getValue().equals(cellData.getStringValue())) {
                    key = entry.getKey();
                    break;
                }
            }
        }
        return key;
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value,
                                               ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(map.get(value));
    }
}
